<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Tuan
{
    private static $_typeid = 13;


    public static function detail($params)
    {
        if ($params['product_id']) {
            $id   = $params['product_id'];
            $mid  = $params['mid'];
            $info = DB::select()->from('tuan')->where('id', '=', $id)->execute()->current();
            if (empty($info)) {
                return array();
            }
            //seo
            $seo_info = Product::seo($info);

            $info['seo_info'] = $seo_info;
            //产品图片
            $piclist = Product::pic_list($info['piclist']);
            $p       = array();
            foreach ($piclist as &$pic) {
                $pi = Model_Api_V2_System::uniapp_img($pic[0], 750, 400);
                array_push($p, $pi);
            }
            if (empty($p)) {
                $p[0] = Model_Api_V2_System::uniapp_img('');
            }
            $info['piclist'] = $p;
            //属性列表
            $info['attrlist'] = Model_Tuan::attr($info['attrid']);

            $info['price'] = Model_Tuan::get_minprice($info['id'], array('info' => $info));

            //会员折扣
            $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::$_typeid, $id, $info['price']);

            //点评数
            $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);
            //销售数量
            $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::$_typeid) + intval($info['virtualnum']);
            //产品编号
            $info['series'] = St_Product::product_series($info['id'], self::$_typeid);
            //产品图标
            $info['iconlist'] = Product::get_ico_list($info['iconlist']);

            //满意度
            $info['score'] = St_Functions::get_satisfy(self::$_typeid, $info['id'], $info['satisfyscore']);

            $info['litpic'] = Model_Api_V2_System::reorganized_resource_url($info['litpic']);

            $info['basehost'] = $GLOBALS['cfg_basehost'];

            $info['content'] = Model_Api_V2_Xcx::filter_content($info['content']);
            //团购状态 1进行中 2未开始
            /* $time = time();
             //已卖完
             if($info['price_type'] == 1 && $info['totalnum'] == 0)
             {
                 $info['status'] = 3;
             }
             else if($info['starttime']<= $time && $time<=$info['endtime'])
             {
                 $info['status'] = 1;
             }else if($info['starttime']> $time)
             {
                 $info['status'] = 2;
             }*/
            $info['status']    = self::getTuanStatus($info);
            $info['starttime'] = intval($info['starttime']);
            $info['endtime']   = intval($info['endtime']);

            //扩展字段信息
            $extend_info         = ORM::factory('tuan_extend_field')
                ->where("productid=" . $info['id'])
                ->find()
                ->as_array();
            $info['extend_info'] = $extend_info;


            //详情内容
            $params              = array(
                'typeid' => self::$_typeid,
                'productinfo' => $info,
                'pc' => 0
            );
            $info['detail_list'] = self::get_detail_content($params);

            // 积分抵现配置
            $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::$_typeid);
            $info['jifentprice_info'] = $jifenprice_info;
            // 预定送积分
            $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::$_typeid);
            $info['jifenbook_info'] = $jifenbook_info;
            //积分评论
            $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::$_typeid);
            $info['jifencomment_info'] = $jifencomment_info;

            return $info;
        } else {
            return array();
        }

    }

    /**
     * @function 获取线路详细行程内容
     * @param $params
     * @return array
     */
    private static function get_detail_content($params)
    {

        $default = array(
            'typeid' => '1',
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );
        $params  = array_merge($default, $params);
        /**
         * @var array $productinfo
         */
        extract($params);
        $arr = DB::select()->from('tuan_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar        = DB::select()->from('tuan_extend_field')->where('productid', '=', $productid)->execute()->as_array();
        $list      = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian' || $v['columnname'] == 'linedoc') {
                continue;
            }
            if ($v['isrealfield'] == 1) {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
                if (empty($content)) {
                    continue;
                }
            }
            $a                = array();
            $a['columnname']  = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            $a['content']     = Model_Api_V2_Xcx::filter_content($content);
            $list[]           = $a;

        }
        return $list;
    }

    /**
     * @function 栏目信息
     * @return mixed
     */
    public static function channel()
    {
        $row = DB::select()->from('nav')->where('typeid', '=', 13)->and_where('issystem', '=', 1)->execute()->current();
        return $row;
    }


    /*
     * 属性生成where条件,用于多条件属性搜索.
     * */
    public static function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        foreach ($arr as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,a.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 团购搜索列表
     * @param $data
     */
    public static function search($params)
    {
        $status    = true;
        $value_arr = array();
        $where     = 'a.ishidden=0 and a.endtime > ' . time();
        //查询目的地ID
        if ($params['destpy'] != 'quanbu' && $params['destpy']) {
            $destId = DB::select('id')->from('destinations')->where('pinyin', '=', $params['destpy'])->execute()->get('id');
            $where  .= " AND FIND_IN_SET('$destId',a.kindlist) ";
        }
        //按状态 1：进行中 2：未开始 0 已过期 3,已售完
        if ($params['status'] == 2) {
            $where .= ' AND a.starttime >' . time();
        }
        if ($params['status'] == 1) {
            $where .= ' AND a.starttime <=' . time() . ' AND a.endtime>' . time();
        }

        //按属性
        if (!empty($params['attrid'])) {
            $where .= Product::get_attr_where($params['attrid']);
        }
        //分页
        if (!isset($params['page'])) {
            $params['page'] = 1;
        }

        $pagesize = $params['pagesize'];
        //偏移量
        $offset = ($params['page'] - 1) * $pagesize;

        //排序
        switch ($params['sorttype']) {
            case 1:
                $order = 'a.price asc,';
                break;
            case 2:
                $order = 'a.price desc,';
                break;
            case 3:
                $order = 'a.virtualnum desc,';
                break;
            case 4:
                $order = 'a.shownum desc,';
                break;
        }
        //关键字
        if (!empty($params['keyword'])) {
            $where                 .= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%' . $params['keyword'] . '%';
        }
        //组合sql
        if ($params['fields']) {
            $fields = $params['fields'];
        } else {
            $fields = "a.id,a.title,a.litpic,a.starttime,a.endtime,a.price,a.sellpoint,a.virtualnum";
        }

        $sql = "SELECT $fields FROM `sline_tuan` a ";
        $sql .= "LEFT JOIN `sline_allorderlist` b ";
        if (empty($destId)) {
            $sql .= 'ON (a.id=b.aid AND b.typeid=13)';
        } else {
            $sql .= "ON (a.id=b.aid AND b.typeid=13 AND b.classid={$destId}) ";
        }
        $sql .= ' WHERE ' . $where;
        $sql .= " ORDER BY {$order} IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";

        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by
        $totalN   = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;
        //检测页面数量是否超限
        $total_page = (int)ceil($totalNum / $pagesize);
        if (($total_page > 0 and intval($params['page']) > $total_page) or ($total_page == 0 and $params['page'] > 1)) {
            $status = false;
        }

        $sql .= " LIMIT {$offset},{$pagesize}";
        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();

        $time = time();
        foreach ($arr as &$v) {

            $v['litpic']    = Model_Api_V2_System::uniapp_img($v['litpic'], 750, 350);
            $v['price']     = Currency_Tool::price($v['price']);
            $v['sellprice'] = Currency_Tool::price($v['sellprice']);
            if ($v['price'] > 0 && $v['sellprice'] > 0) {
                $v['discount'] = $v['price'] == $v['sellprice'] ? '0' : round($v['price'] / $v['sellprice'], 2) * 10;
            } else {
                $v['discount'] = 0;
            }
            $v['sellnum']   = Model_Member_Order::get_sell_num($v['id'], 13) + intval($v['virtualnum']);
            $v['iconlist']  = Product::get_ico_list($v['iconlist']);
            $v['endtime']   = intval($v['endtime']);
            $v['starttime'] = intval($v['starttime']);
            //$v['jsendtime'] = date('Y/m/d H:i:s',$v['endtime']);
            //状态
            $v['status'] = self::getTuanStatus($v);
            //倒计时时间,采用13位时间戳,需要*1000
            $v['count_time']   = ($v['status'] == 1 ? $v['endtime'] - $time : $v['starttime'] - $time) * 1000;
            $v['satisfyscore'] = St_Functions::get_satisfy(self::$_typeid, $v['id'], $v['satisfyscore'], array('suffix' => ''));
            $v['expire']       = ($v['starttime'] <= time() && $v['endtime'] >= time()) ? 0 : 1;
            $v['coming']       = $v['starttime'] > time() ? 1 : 0;

        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr,
            'status' => $status
        );
        return $out;
    }

    /**
     * 获取团购产品的状态
     * @param $row
     * @return int
     */
    public static function getTuanStatus($row)
    {
        //按状态 1：进行中 2：未开始 0 已过期 3,已售完
        $time = time();
        //已过期
        if ($row['endtime'] < $time) {
            return 0;
        } //进行中
        else if ($row['starttime'] < $time && $time < $row['endtime']) {
            //检测是否卖完
            if ($row['price_type'] == 1 && $row['totalnum'] == 0) {
                return 3;
            } else if ($row['price_type'] == 2) {
                $totalnum = DB::select(DB::expr("sum(number) as total"))
                    ->from('tuan_price')
                    ->where('tuan_id', '=', $row['id'])
                    ->execute()
                    ->get('total');
                if ($totalnum == 0) {
                    return 3;
                }
            }
            return 1;
        } else if ($time < $row['starttime']) {
            return 2;
        }

    }

    public static function get_buy_num_limit($tuan_id, $limit_order, $mid, $usedate)
    {
        $info = DB::select()->from('tuan')->where('id', '=', $tuan_id)->execute()->current();
        if ($info['price_type'] == 1) {
            // 0 不限购 预定数量为产品数量
            if ($limit_order == '0') {
                $totalnum      = DB::select('totalnum')->from('tuan')->where('id', '=', $tuan_id)->execute()->get('totalnum');
                $buy_num_limit = $totalnum == -1 ? 1000 : $totalnum;
            } else {
                $bought_num    = Model_Tuan::get_bought_num($mid, null, $tuan_id);
                $buy_num_limit = intval($limit_order) - $bought_num;
            }
        } //日历
        else if ($info['price_type'] == 2) {
            $day = strtotime($usedate);
            // 0 不限购 预定数量为产品数量
            if ($limit_order == '0') {
                $totalnum      = DB::select('number')->from('tuan_price')
                    ->where('tuan_id', '=', $tuan_id)
                    ->and_where('day', '=', $day)
                    ->execute()->get('number');
                $buy_num_limit = $totalnum;
            } else {
                $bought_num    = Model_Tuan::get_bought_num($mid, null, $tuan_id);
                $buy_num_limit = intval($limit_order) - $bought_num;
            }
        }
        return $buy_num_limit;
    }

    /**
     * 通过提交的参数创建订单数据
     */
    public static function make_order($memberid, $request_data)
    {
        try {
            if (!$memberid) {
                throw new Exception('请登录');
            }
            $productautoid = intval($request_data->productautoid);

            //收货地址
            $address_id = $request_data->address_id;
            $dingnum    = intval($request_data->ding_num);
            if (!$productautoid) {
                throw new Exception('产品id为空');
            }

            $userInfo = Model_Member::get_member_info($memberid);
            if (!$userInfo) {
                throw new Exception('用户信息有误,未找到会员');
            }

            //产品信息
            $info = DB::select()->from('tuan')->where('id', '=', $productautoid)->execute()->current();

            //收货地址验证
            $receiver_address_id = 0;
            if ($memberid) {
                $receiver_address_id = $address_id;
                if (!Model_Member_Address::check_address_id($memberid, $receiver_address_id)) {
                    $receiver_address_id = 0;
                }
            }

            // 快递计划
            $express_total_price = 0;
            $express_plan_id = intval($request_data->express_plan_id);
            if (!empty($info['freightid']) && $info['receive_address'] == 1) {
                $plan_info = null;
                if ($memberid) {
                    $plan_info = Model_Express_Plan::get_plan($info['freightid'], $receiver_address_id);
                }
                if ($plan_info['status'] == 0 || $plan_info['data']['id'] != $express_plan_id) {
                    throw new Exception('快递信息有误');
                }
                $express_price       = Model_Express_Plan::get_freight_price($info, $plan_info['data'], $dingnum);
                $express_total_price = floatval($express_price);
            }

            //下架状态判断
            if ($info['ishidden'] != 0) {
                throw new Exception('当前产品已下架，不可预订');
            }

            $current_time = time();
            if ($current_time < $info['starttime'] || $current_time > $info['endtime']) {
                throw new Exception('当前产品已过期或失效,暂不能预订,请联系客服!');
            }

            //限购判断
            $buy_num_limit = Model_Api_V2_Tuan::get_buy_num_limit($info['id'], $info['limit_order'], $memberid, $request_data->use_date);
            if ($buy_num_limit <= 0) {
                throw new Exception('已达到购买上限,暂不能预订,请联系客服!');
            }

            $linkman   = trim(Common::remove_xss($request_data->linkman));
            $linktel   = trim(Common::remove_xss($request_data->linktel));
            $linkemail = Common::remove_xss($request_data->linkemail);

            // 检查联系人和联系电话
            if (!$linkman || !$linktel) {
                throw new Exception('请填写联系人信息!');
            }

            // 备注信息
            $remark = Common::remove_xss($request_data->remark);

            //积分抵现.
            $needJifen   = intval($request_data->needjifen);
            $jifentprice = 0;
            $useJifen    = 0;
            if ($needJifen) {
                $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], 1, $needJifen, $userInfo);
                $useJifen    = empty($jifentprice) ? 0 : 1;
                $needJifen   = empty($jifentprice) ? 0 : $needJifen;
            }

            //积分评论
            $jifencomment_info = Model_Jifen::get_used_jifencomment(13);
            $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

            // 订单数据
            $order = array(
                'litpic' => $info['litpic'],
                'typeid' => 13,
                'productautoid' => $productautoid,
                'productaid' => $info['aid'],
                'productname' => $info['title'],
                'departdate' => '',
                'webid' => 0,
                'addtime' => time(),
                'linkman' => $linkman,
                'linktel' => $linktel,
                'linkemail' => $linkemail,
                'remark' => $remark,
                'usejifen' => $useJifen,
                'needjifen' => $needJifen,
                'jifentprice' => $jifentprice,
                'jifenbook' => $info['jifenbook_id'],
                'jifencomment' => $jifencomment,
                'memberid' => $memberid,
                'suitid' => 0,
                'childnum' => 0,
                'oldnum' => 0,
                'people4_num' => 0,
                'people5_num' => 0,
                'people6_num' => 0,
                'roombalancenum' => 0,
                'roombalance_paytype' => 1,
                'receiver_address_id' => $receiver_address_id,
                'receiver_address_infos'=>json_encode(Db::select('province','city','area','receiver','phone','postcode','address')->from('member_address')->where('id','=',$receiver_address_id)->execute()->current(),JSON_UNESCAPED_UNICODE),
                'express_total_price' => $express_total_price,
            );

            //成人数量
            if ($dingnum) {
                $order['dingnum'] = $dingnum;
            }
            //自动关闭订单时间
            $auto_close_time = $info['auto_close_time'] ? $info['auto_close_time'] : 0;
            if ($auto_close_time) {
                $order['auto_close_time'] = $auto_close_time + time();
            }
            //收货地址
            if ($address_id) {
                $order['receiver_address_id'] = $address_id;
            }
            //出发日期
            $usedate = $request_data->use_date;
            if ($usedate) {
                $order['usedate'] = $usedate;
            }

            //日历 or 普通报价
            if ($info['price_type'] == 1) {
                $price = $info['price'];
            } else if ($info['price_type'] == 2) {
                $row   = DB::select('price')->from('tuan_price')
                    ->where('tuan_id', '=', $productautoid)
                    ->and_where('day', '=', strtotime($usedate))
                    ->execute()
                    ->current();
                $price = $row['price'];
            }

            // 二次确认支付
            $order['status']             = $info['paytype'] == 3 ? 0 : 1;
            $order['paytype']            = $info['paytype'];
            $order['dingjin']            = doubleval($info['dingjin']);
            $order['price']              = $price;
            $order['childprice']         = 0;
            $order['oldprice']           = 0;
            $order['people4_price']      = 0;
            $order['people5_price']      = 0;
            $order['people6_price']      = 0;
            $order['roombalance']        = 0;
            $order['suit_name']          = '';
            $order['refund_restriction'] = $info['refund_restriction'];

            // 处理优惠券
            $couponid = $request_data->coupon_id;
            if ($couponid) {
                $cid        = DB::select('cid')->from('member_coupon')->where("id={$couponid}")->execute()->current();
                $totalprice = (new Model_Coupon)->get_order_totalprice($order);
                $ischeck    = Model_Api_V2_Coupon::check_samount($couponid, $totalprice, $order['typeid'], $order['productautoid'], 0, $memberid);
                if ($ischeck['status'] != 1) {
                    throw new Exception('优惠券不满足使用条件!');
                } else {
                    $coupon = compact('cid', 'totalprice', 'ischeck', 'couponid');
                }
            }
            // 订单来源 1PC,2WAP,3小程序,4平台添加
            $order['source'] = $request_data->source;

            return array(
                'status' => true,
                'data' => $order,
                'coupon' => isset($coupon) ? $coupon : '', // 优惠券使用
                'msg' => ''
            );
        } catch (Exception $e) {
            return array(
                'status' => false,
                'data' => '',
                'msg' => $e->getMessage()
            );
        }
    }
}